package org.smarthings.mqtt;

import org.eclipse.paho.client.mqttv3.MqttClient;
import org.eclipse.paho.client.mqttv3.MqttException;
import org.eclipse.paho.client.mqttv3.persist.MemoryPersistence;
import org.smarthings.Callback;
import org.smarthings.Client;
import org.smarthings.Message;
import org.smarthings.Response;
import org.smarthings.Utils;

public class MqttClientImpl implements Client {
	private MqttClient client;
	private MqttCallbackImpl callback;

	public void start(String host, int port) {
		try {
			client = new MqttClient("tcp://" + host + ":" + port, MqttClient.generateClientId(),
					new MemoryPersistence());
			callback = new MqttCallbackImpl();
			client.setCallback(callback);
			client.connect();
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

	public void stop() {
		try {
			client.disconnect();
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}

	public String getProtocol() {
		return MqttFactory.PROTOCOL;
	}

	public Response post(Message message) {
		try {
			client.publish(message.getUri(), message.getPayload(), 0, true);
		} catch (MqttException e) {
			e.printStackTrace();
		}
		return Response.getEmptyResponse();
	}

	public Response post(String uri, Message message) {
		try {
			client.publish(uri, message.getPayload(), 0, true);
		} catch (MqttException e) {
			e.printStackTrace();
		}
		return Response.getEmptyResponse();
	}

	public Message get(String uri, String contentType) {
		return null;
	}

	public void subscribe(String topic, String contentType, Callback handler) {
		try {
			String uri = Utils.normalizeUri(topic);
			callback.addCallback(uri, handler);
			client.subscribe(uri);
		} catch (MqttException e) {
			e.printStackTrace();
		}
	}
}
